
package com.ybkj.o2o.mc.controller.res;

import com.google.common.base.Preconditions;
import com.google.gson.Gson;
import com.alibaba.fastjson.JSON;
import com.ybkj.o2o.mc.common.DataGrid;
import com.ybkj.o2o.mc.common.PhoneNumberHelper;
import com.ybkj.o2o.mc.common.query.DepartmentQuery;
import com.ybkj.o2o.mc.common.query.EnterpriseQuery;
import com.ybkj.o2o.mc.common.transport.Error;
import com.ybkj.o2o.mc.common.transport.Result;
import com.ybkj.o2o.mc.entity.Department;
import com.ybkj.o2o.mc.entity.Enterprise;
import com.ybkj.o2o.mc.entity.Passenger;
import com.ybkj.o2o.mc.entity.PassengerAccount;
import com.ybkj.o2o.mc.entity.PassengerGrade;
import com.ybkj.o2o.mc.entity.PassengerManage;
import com.ybkj.o2o.mc.manager.DepartmentManager;
import com.ybkj.o2o.mc.manager.EnterpriseManager;
import com.ybkj.o2o.mc.manager.PassengerGradeManager;
import com.ybkj.o2o.mc.manager.PassengerManageManager;
import com.ybkj.o2o.mc.manager.PassengerManager;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;












import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by shine on 15/8/25.
 */
@RestController
@RequestMapping(value = "api/enterprises")
public class EnterpriseRes {

  @Autowired
  private EnterpriseManager enterpriseManager;

  @Autowired
  private PassengerGradeManager gradeManager;
  
  @Autowired
  private DepartmentManager departmentManager;

  @Autowired
  private PassengerManager passengerManager;
  
  @Autowired
  private PassengerManageManager passengerManageManager;

  /**
   * 创建企业.
   */
  @Transactional(rollbackFor=Exception.class) 
  @RequestMapping(value = {"", "/"}, method = RequestMethod.POST)
  public ResponseEntity<Object> create(
          @RequestParam("name") String name,
          @RequestParam(value = "address", required = false) String address,
          @RequestParam(value = "memo", required = false) String memo,
          @RequestParam(required = false, value = "allowOverdraw") Boolean allowOverdraw,
          @RequestParam(required = false, value = "grade_id") Long gradeId,
          @RequestParam(required = false, value = "manageAccount") String manageAccount,
          @RequestParam(required = false, value = "managePassword") String managePassword,
          @RequestParam("companyId") Long companyId,
          @RequestParam("companyName") String companyName,
          @RequestParam("appKey") String appKey) {

    ResponseEntity<Object> responseEntity = null;

    name = StringUtils.trimToEmpty(name);
    companyName = StringUtils.trimToEmpty(companyName);
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(StringUtils.isNotBlank(name), "企业名称不能为空");
    Preconditions.checkArgument(companyId != null && companyId != 0, "所属公司Id不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(companyName), "所属公司名称不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    //验证企业信息是否已经存在
    boolean exists = enterpriseManager.exists(name, appKey, companyId);
    
    if (exists) {
		  Result<Enterprise> result = new Result<>(-2, "企业名称已存在", null);

	      responseEntity = new ResponseEntity<>(result, HttpStatus.NOT_IMPLEMENTED);

	      return responseEntity;
	  }
    
    //保存企业信息
    try {

      Enterprise enterprise = new Enterprise();
      enterprise.setName(name);
      enterprise.setAddress(address);
      enterprise.setMemo(memo);
      enterprise.setAllowOverdraw(BooleanUtils.toBoolean(allowOverdraw));
      enterprise.setCompanyId(companyId);
      enterprise.setCompanyName(companyName);
      enterprise.setAppKey(appKey);
      enterprise.setDrawMoney(0.0);
      enterprise.setFrozenMoney(0.0);
      enterprise.setNodrawMoney(0.0);

      PassengerGrade grade = null;

      if (null != gradeId) {
        grade = gradeManager.fetch(gradeId, null,  appKey);

      } else {
        grade = gradeManager.findDefault(companyId,appKey);
      }

      if (grade != null) {
        enterprise.setGradeId(grade.getId());
        enterprise.setGradeName(grade.getName());
      }

      enterprise = enterpriseManager.insert(enterprise);
      
      //添加企业管理员
      if( null != enterprise && StringUtils.isNotBlank(manageAccount)){
    	  PassengerManage passengerManage = new PassengerManage();
    	  passengerManage.setManageAccount(manageAccount);
    	  PassengerManage passengerManageNew = passengerManageManager.findPassengerManagerByParam(passengerManage);
    	  if (null != passengerManageNew) {
    		  enterpriseManager.deleteEnterprise(enterprise.getId(), appKey);
    		  Result<Enterprise> result = new Result<>(-2, "已存在相同名称的企业管理员", null);

    	      responseEntity = new ResponseEntity<>(result, HttpStatus.NOT_IMPLEMENTED);

    	      return responseEntity;
    	  }
    	  passengerManage.setEnterpriseId(enterprise.getId());
    	  passengerManage.setEnterpriseName(enterprise.getName());
    	  passengerManage.setManagePassword(managePassword);
    	  passengerManage.setManageGrade(0);
    	  passengerManage.setAppKey(appKey);
    	  
    	  passengerManage = passengerManageManager.insert(passengerManage);
    	  
    	  
      }

      Result<Enterprise> result = new Result<>(0, "成功", enterprise);

      responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);

      return responseEntity;

    } catch (Exception ex) {

      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }

  }

  /**
   * 批量添加企业下的客户 .
   */
  @RequestMapping(value = {"{enterpriseId}/passengers"}, method = RequestMethod.POST)
  public ResponseEntity<Object> createPassengers(@PathVariable("enterpriseId") Long enterpriseId,
                                                 @RequestParam("passengers") String passengers,
                                                 @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(StringUtils.isNotBlank(passengers), "客户信息不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    try {
      Enterprise enterprise = enterpriseManager.findByIdAndAppKey(enterpriseId, appKey);

      List<Passenger> passengerList = JSON.parseArray(passengers, Passenger.class);

      boolean matches = passengerList.stream()
              .allMatch(p -> PhoneNumberHelper.isPhoneOrTel(p.getPhone()));

      if (!matches) {
        Result<Passenger> result = new Result<>(-1, "乘客电话号码不合法", null);
        responseEntity = new ResponseEntity<>(result, HttpStatus.UNPROCESSABLE_ENTITY);
        return responseEntity;
      }

      List<String> phones = passengerList.stream()
              .map(p -> p.getPhone()).collect(Collectors.toList());

      boolean exists = passengerManager.existsByPhones(phones, appKey);

      if (exists) {
        Result<Passenger> result = new Result<>(-1, "乘客信息中存在相同的电话号码", null);
        responseEntity = new ResponseEntity<>(result, HttpStatus.UNPROCESSABLE_ENTITY);
        return responseEntity;
      }

      enterpriseManager.batchInsert(passengerList, enterprise);

      Result<Enterprise> result = new Result<>(0, "成功", enterprise);

      responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);

      return responseEntity;

    } catch (Exception ex) {

      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }
  }


  /**
   * 批量修改企业下的乘客.
   */
  @RequestMapping(value = {"{enterpriseId}/updatePassengers"}, method = RequestMethod.PUT)
  public ResponseEntity<Object> updatePassengers(
          @PathVariable("enterpriseId") Long enterpriseId,
          @RequestParam("passengers") String passengers,
          @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(StringUtils.isNotBlank(passengers), "客户信息不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    try {
      Enterprise enterprise = enterpriseManager.findByIdAndAppKey(enterpriseId, appKey);
      List<Passenger> passengerList = JSON.parseArray(passengers, Passenger.class);
      for (Passenger p : passengerList) {
        p.setCreated(new Date());
        p.setUpdated(new Date());
        p.setAppKey(appKey);
      }
      boolean matches = passengerList.stream()
              .allMatch(p -> PhoneNumberHelper.isPhoneOrTel(p.getPhone()));

      if (!matches) {
        Result<Passenger> result = new Result<>(-1, "乘客电话号码不合法", null);
        responseEntity = new ResponseEntity<>(result, HttpStatus.UNPROCESSABLE_ENTITY);
        return responseEntity;
      }

      enterpriseManager.updatePassengers(passengerList, enterprise);

      Result<Enterprise> result = new Result<>(0, "成功", enterprise);

      responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);

      return responseEntity;

    } catch (Exception ex) {

      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }
  }

  /**
   * 修改企业基本信息.
   */
  @Transactional(rollbackFor = Exception.class)
  @RequestMapping(value = "{enterpriseId}", method = RequestMethod.PUT)
  public ResponseEntity<Object> update(
          @PathVariable("enterpriseId") Long enterpriseId,
          @RequestParam(value = "name", required = false) String name,
          @RequestParam(value = "address", required = false) String address,
          @RequestParam(value = "memo", required = false) String memo,
          @RequestParam(value = "allowOverdraw", required = false) Boolean allowOverdraw,
          @RequestParam(value = "grade_id", required = false) Long gradeId,
          @RequestParam(required = false, value = "manageAccount") String manageAccount,
          @RequestParam(required = false, value = "managePassword") String managePassword,
          @RequestParam(value = "companyId", required = false) Long companyId,
          @RequestParam(value = "companyName", required = false) String companyName,
          @RequestParam(value = "drivingNumberTimes", required = false) Long drivingNumberTimes,
          @RequestParam("appKey") String appKey) {

    ResponseEntity<Object> responseEntity = null;

    name = StringUtils.trimToEmpty(name);
    
    companyName = StringUtils.trimToEmpty(companyName);
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(enterpriseId != null && enterpriseId != 0, "企业Id不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    //修改企业信息
    try {

      Enterprise enterprise = enterpriseManager.findOne(enterpriseId, appKey);
      
      Gson gson = new Gson();
      
      Boolean isExists = enterpriseManager.exists(name, appKey, companyId);
      
      if(!enterprise.getName().equals(name) && isExists){
    	  Result<Enterprise> result = new Result<>(-2, "同一个公司下已存在相同名称的企业", null);

	      responseEntity = new ResponseEntity<>(result, HttpStatus.NOT_IMPLEMENTED);

	      return responseEntity;
      }
      
//    enterprise.setId(enterpriseId);
      enterprise.setName(name);
      enterprise.setCompanyId(companyId);
      enterprise.setCompanyName(companyName);
      if (gradeId != null) {
    	  PassengerGrade grade = gradeManager.fetch(gradeId, null, appKey);
    	  if (grade != null) {
    		  enterprise.setGradeId(gradeId);
    		  enterprise.setGradeName(grade.getName());
    	  }
      }
      enterprise.setAddress(address);
      enterprise.setMemo(memo);
      enterprise.setAllowOverdraw(allowOverdraw);
      enterprise.setDrivingNumberTimes(drivingNumberTimes);
      
      if (StringUtils.isNotBlank(manageAccount)) {
        PassengerManage passengerManage = new PassengerManage();
        passengerManage.setEnterpriseId(enterprise.getId());
        passengerManage.setEnterpriseName(enterprise.getName());
        passengerManage.setManageGrade(0);
        
        PassengerManage passengerManageNew = passengerManageManager.findPassengerManagerByParam(passengerManage);
        
        passengerManage.setManageAccount(manageAccount);
        
        PassengerManage passengerManageByAccount = new PassengerManage();
        passengerManageByAccount.setManageAccount(manageAccount);
        
        passengerManageByAccount = passengerManageManager.findPassengerManagerByParam(passengerManageByAccount);
        
        if(null != passengerManageNew){
          if (!passengerManageNew.getManageAccount().equals(manageAccount) && null != passengerManageByAccount) {
            Result<Enterprise> result = new Result<>(-2, "已存在相同名称的企业管理员", null);
            
            responseEntity = new ResponseEntity<>(result, HttpStatus.NOT_IMPLEMENTED);
            
            return responseEntity;
          }
        }
        if ( null != managePassword) {
          passengerManage.setManagePassword(managePassword);
        }
        passengerManage.setAppKey(appKey);
        
        passengerManager.updateEnterpriseName(enterprise.getId(),enterprise.getName(), appKey);
        passengerManager.updateAllowOverdraw(enterprise.getId(),enterprise.getAllowOverdraw(),appKey);
        if (gradeId != null) {
      	  PassengerGrade grade = gradeManager.fetch(gradeId, null, appKey);
      	  if (grade != null) {
      		  passengerManager.updateGradeByEnterpriseId(enterpriseId,grade.getId(),grade.getName(),appKey);
      	  }
        }
        
        int updateRows = passengerManageManager.update(passengerManage);
        if(updateRows == 0){
        	if( StringUtils.isNotBlank(passengerManage.getManagePassword())){
        		passengerManageManager.insert(passengerManage);
        	}else {
        		Result<Enterprise> result = new Result<>(-2, "当前企业暂无管理员，请输入密码", null);
                
                responseEntity = new ResponseEntity<>(result, HttpStatus.NOT_IMPLEMENTED);
                
                return responseEntity;
			}
        }
      }
      
      enterpriseManager.update(enterprise);
      departmentManager.updateEnterpriseNameByEnterpriseId(enterprise.getId(),enterprise.getName(), appKey);

      Result<Enterprise> result = new Result<>(0, "成功", null);

      responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);

      return responseEntity;

    } catch (Exception ex) {

      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }

  }

  /**
   * 删除企业.
   */
  @RequestMapping(value = "{enterpriseId}", method = RequestMethod.DELETE)
  public ResponseEntity<Object> delete(@PathVariable("enterpriseId") Long enterpriseId,
                                       @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;

    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(enterpriseId != null && enterpriseId != 0, "企业Id不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    //验证企业信息是否已经存在
    Enterprise enterprise = enterpriseManager.findByIdAndAppKey(enterpriseId, appKey);

    Preconditions.checkArgument(enterprise != null, "企业不存在");

    DepartmentQuery departmentQuery = new DepartmentQuery();
    departmentQuery.setEnterpriseId(enterpriseId);
    
    DataGrid<Department> departmentDataGrid = departmentManager.findByDepartmentQuery(departmentQuery);
    
    Gson gson = new Gson();
    
    PassengerManage passengerManage = new PassengerManage();
    	
	if(null!=departmentDataGrid){
    	List<Department> departments = departmentDataGrid.getRows();
    	List<Long> departmentIds = new ArrayList<>();
    	
    	
    	if(!departments.isEmpty()){
    		for (Department department : departments) {
    			passengerManage.setDepartmentId(department.getId());
    			passengerManager.updateByDelDepartment(department.getId(),appKey);
    			passengerManageManager.deleteByParam(passengerManage);
    			departmentIds.add(department.getId());
    		}
    		departmentManager.batchDeleteByIds(departmentIds,appKey);
    	}
    }
    
	
    List<Passenger> passengers = passengerManager.findByEnterprise(enterpriseId, appKey);
    if(!passengers.isEmpty()){
    	List<Long> passengerIds = new ArrayList<>();
    	for (Passenger passenger : passengers) {
			passengerIds.add(passenger.getId());
		}
    	passengerManager.batchUpdateByIds(passengerIds,appKey);
    }
    
    try {
      PassengerManage passengerManageNew = new PassengerManage();
      passengerManageNew.setEnterpriseId(enterpriseId);
      passengerManageManager.deleteByParam(passengerManageNew);
    	
      enterpriseManager.deleteEnterprise(enterpriseId, appKey);
      
      Result<PassengerGrade> result = new Result<>(0, "成功", null);

      responseEntity = new ResponseEntity<>(result, HttpStatus.NO_CONTENT);

      return responseEntity;

    } catch (Exception ex) {

      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }

  }

  /**
   * 企业充值.
   */
  @RequestMapping(value = "{enterpriseId}/accountDetail", method = RequestMethod.POST)
  public ResponseEntity<Object> createAccount(
          @PathVariable("enterpriseId") Long enterpriseId,
          @RequestParam(required = false, value = "departmentId") Long departmentId,
          @RequestParam(required = false, value = "departmentName") String departmentName,
          @RequestParam("money") Double money,
          @RequestParam("payType") String payType,
          @RequestParam("operator") String operator,
          @RequestParam("updateBlance") Boolean updateBlance,
          @RequestParam(required = false, value = "useNoDrawMoney") Boolean useNoDrawMoney,
          @RequestParam(required = false, value = "details") String details,
          @RequestParam(required = false, value = "tradeNo") String tradeNo,
          @RequestParam(required = false, value = "orderNo") String orderNo,
          @RequestParam(required = false, value = "passenger_id") Long passenger_id,
          @RequestParam(required = false, value = "passenger_phone") String passenger_phone,
          @RequestParam(required = false, value = "passenger_name") String passenger_name,
          @RequestParam(required = false, value = "orderId") Long orderId,
          @RequestParam(required = false, value = "orderType") Integer orderType,
          @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;

    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(payType), "支付类型不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(operator), "操作人不能为空");
    Enterprise enterprise = enterpriseManager.findByIdAndAppKey(enterpriseId, appKey);
    Preconditions.checkArgument(enterprise != null, "企业不存在");

    try {

      updateBlance = BooleanUtils.toBoolean(updateBlance);
      useNoDrawMoney = BooleanUtils.toBoolean(useNoDrawMoney);

      PassengerAccount account = new PassengerAccount();
      account.setEnterpriseId(enterpriseId);
      account.setEnterpriseName(enterprise.getName());
      account.setDepartmentId(departmentId);
      account.setDepartmentName(departmentName);
      account.setMoney(money);
      account.setOrderNo(orderNo);
      account.setPassengerId(passenger_id);
      account.setPassengerName(passenger_name);
      account.setPassengerPhone(passenger_phone);
      account.setOrderId(orderId);
      account.setOrderType(orderType);
      account.setDetails(details);
      account.setTradeNo(tradeNo);
      account.setPayType(payType);
      account.setOperator(operator);
      account.setAppKey(appKey);
      account.setCompanyId(enterprise.getCompanyId());

      account = enterpriseManager.updateAccount(enterprise, account, updateBlance, useNoDrawMoney);

      Result<PassengerAccount> result = new Result<>(0, "成功", account);
      responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);

      return responseEntity;

    } catch (Exception ex) {

      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }
  }

  /**
   * 修改企业不可提现金额.
   */
  @RequestMapping(value = "{enterpriseId}/accountNoDrawMoney", method = RequestMethod.POST)
  public ResponseEntity<Object> accountNoDrawMoney(
          @PathVariable("enterpriseId") Long enterpriseId,
          @RequestParam("money") Double money,
          @RequestParam("payType") String payType,
          @RequestParam("operator") String operator,
          @RequestParam("updateBlance") Boolean updateBlance,
          @RequestParam(required = false, value = "details") String details,
          @RequestParam(required = false, value = "tradeNo") String tradeNo,
          @RequestParam(required = false, value = "orderNo") String orderNo,
          @RequestParam(required = false, value = "orderId") Long orderId,
          @RequestParam(required = false, value = "orderType") Integer orderType,
          @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;

    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(payType), "支付类型不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(operator), "操作人不能为空");
    Enterprise enterprise = enterpriseManager.findByIdAndAppKey(enterpriseId, appKey);
    Preconditions.checkArgument(enterprise != null, "企业不存在");

    try {

      PassengerAccount account = new PassengerAccount();
      account.setEnterpriseId(enterpriseId);
      account.setEnterpriseName(enterprise.getName());
      account.setMoney(money);
      account.setOrderNo(orderNo);
      account.setOrderId(orderId);
      account.setOrderType(orderType);
      account.setDetails(details);
      account.setTradeNo(tradeNo);
      account.setPayType(payType);
      account.setOperator(operator);
      account.setAppKey(appKey);
      account.setCompanyId(enterprise.getCompanyId());

      account = enterpriseManager.accountNoDrawMoney(enterprise, account, updateBlance);

      Result<PassengerAccount> result = new Result<>(0, "成功", account);
      responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);

      return responseEntity;

    } catch (Exception ex) {

      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }
  }

  /**
   * 查询企业的信息(包括旗下乘客).
   */
  @RequestMapping(value = "{enterpriseId}", method = RequestMethod.GET)
  public ResponseEntity<Object> getEnterprise(@PathVariable("enterpriseId") Long enterpriseId,
                                              @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;

    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(enterpriseId != null && enterpriseId != 0, "企业Id不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    //验证企业信息是否已经存在
    Enterprise enterprise = enterpriseManager.findByIdAndAppKey(enterpriseId, appKey);

    Preconditions.checkArgument(enterprise != null, "企业不存在");

    try {
      List<Passenger> list = passengerManager.findByEnterprise(enterpriseId, appKey);
      Long drivingNumberTimes = 0L;

      for (int i = 0; i < list.size(); i++) {
        drivingNumberTimes += list.get(i).getDrivingNumberTimes();
      }
      enterprise.setPassengers(list);
      enterprise.setDrivingNumberTimes(drivingNumberTimes);
      Result<Enterprise> result = new Result<>(0, "成功", enterprise);

      responseEntity = new ResponseEntity<>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {

      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }

  }


  /**
   * 分页查询企业.
   */
  @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
  public ResponseEntity<Object> findByParam(
          @RequestParam(required = false, value = "gradeId") Long gradeId,
          @RequestParam(required = false, value = "companyId") Long companyId,
          @RequestParam(required = false, value = "start") Long start,
          @RequestParam(required = false, value = "end") Long end,
          @RequestParam(required = false, value = "param") String param,
          @RequestParam(required = false, value = "page") Integer page,
          @RequestParam(required = false, value = "rows") Integer rows,
          @RequestParam(required = false, value = "appKey") String appKey) {

	    ResponseEntity<Object> responseEntity = null;
	
	    appKey = StringUtils.trimToEmpty(appKey);
	    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
	
	
	    EnterpriseQuery enterpriseQuery = new EnterpriseQuery();
	    if (gradeId != null) {
	      enterpriseQuery.setGradeIds(new Long[]{gradeId});
	    }
	    enterpriseQuery.setStartTime(start);
	    enterpriseQuery.setEndTime(end);
	    enterpriseQuery.setCompanyId(companyId);
	    enterpriseQuery.setKeyword(param);
	    enterpriseQuery.setAppKey(appKey);
	    enterpriseQuery.setPage(page);
	    enterpriseQuery.setRows(rows);
	
	    return getEnterpriseForPage(enterpriseQuery);
	  }

  /**
   * 后台查询企业信息.
   */
  @RequestMapping(value = "listData", method = RequestMethod.GET)
  public ResponseEntity<Object> listData(
          @RequestParam(required = false, value = "companyId") Long companyId,
          @RequestParam(required = false, value = "grade") Long[] grade,
          @RequestParam(required = false, value = "companyName") String companyName,
          @RequestParam(required = false, value = "start") Long start,
          @RequestParam(required = false, value = "end") Long end,
          @RequestParam(required = false, value = "address") String address,
          @RequestParam(required = false, value = "name") String name,
          @RequestParam(required = false, value = "page") Integer page,
          @RequestParam(required = false, value = "rows") Integer rows,
          @RequestParam("appKey") String appKey) {

    ResponseEntity<Object> responseEntity = null;

    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    EnterpriseQuery enterpriseQuery = new EnterpriseQuery();
    enterpriseQuery.setGradeIds(grade);
    enterpriseQuery.setStartTime(start);
    enterpriseQuery.setEndTime(end);
    enterpriseQuery.setCompanyId(companyId);
    enterpriseQuery.setCompanyName(companyName);
    enterpriseQuery.setAddress(address);
    enterpriseQuery.setName(name);
    enterpriseQuery.setAppKey(appKey);
    enterpriseQuery.setPage(page);
    enterpriseQuery.setRows(rows);

    return getEnterpriseForPage(enterpriseQuery);
  }

  private ResponseEntity<Object> getEnterpriseForPage(EnterpriseQuery enterpriseQuery) {

    ResponseEntity<Object> responseEntity;

    try {
    	
      DataGrid<Enterprise> dataGrid = enterpriseManager.findByEnterpriseQuery(enterpriseQuery);
      
      Result<DataGrid<Enterprise>> result = new Result<>(0, "成功", dataGrid);

      responseEntity = new ResponseEntity<>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {

      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }
  }
  
}
